let http = require('http')
let fs = require('fs')
let path = require('path')
let mime = require('mime')

function send404(response) {
    response.writeHead(404, {'Content-Type': 'text/plain'})
    response.write('Error 404: resource not found.')
    response.end()
}

function sendFile(response, filePath, fileContents) {
    response.writeHead(200, {
        'Content-Type': mime.lookup(path.basename(filePath))
    })
    response.end(fileContents)
}

function serveStatic(response, absPath) {
    fs.exists(absPath, exists => {
        if (exists) {
            fs.readFile(absPath, (err, data) => {
                if (err) {
                    send404(response)
                } else {
                    sendFile(response, absPath, data)
                }
            })
        } else {
            send404(response)
        }
    })
}

let server = http.createServer((request, response) => {
    let filePath = false;

    if (request.url === '/') {
        filePath = 'public/index.html'
    } else {
        filePath = 'public' + request.url
    }
    
    let absPath = './' + filePath
    serveStatic(response, absPath)
})

module.exports = () => {
    server.listen(3000, function () {
        console.log('Server listening on port 3000')
    })
}
